package com.example.apigateway.filter;

import com.example.apigateway.Utils.AesUtil;
import com.example.apigateway.dataobject.KabaoUser;
import com.example.apigateway.service.UserService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 用户权限校验
 */
@Component
public class AuthFilter extends ZuulFilter{

    @Autowired
    private UserService userService;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //针对特定请求做过滤
        if("/kabaouser/user/info".equals(request.getRequestURI())) {
            return true;
        }
        if("/tenantbank/card/list".equals(request.getRequestURI())) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //校验登录与否
        String token = request.getHeader("Access-User-Token");
        if(StringUtils.isEmpty(token)) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            return null;
        }
        String access_user_token = AesUtil.decryptData(token);
        if(StringUtils.isEmpty(access_user_token)) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            return null;
        }
        KabaoUser kabaoUser = userService.findByToken(access_user_token);
        if(kabaoUser == null) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            return null;
        }

        //校验用户登陆时间是否过期
        if(kabaoUser.getStatus() != 1 && new Date().getTime()/1000 > kabaoUser.getTimeout().getTime()/1000) {
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            return null;
        }
        
        return null;
    }
}
